package cn.cs.service.impl;

import cn.cs.client.RestRepairUserClient;
import cn.cs.client.ShopOrderClient;
import cn.cs.common.*;
import cn.cs.pojo.RepairUser;
import cn.cs.pojo.ShopOrder;
import cn.cs.service.ShopOrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

@Service
public class ShopOrderServiceImpl implements ShopOrderService {

    @Resource
    private ShopOrderClient shopOrderClient;

    @Resource
    private RestRepairUserClient repairUserClient;

    @Resource
    private RedisUtils redisUtils;
    public ShopOrder getShopOrderById(Long id)throws Exception{
        return shopOrderClient.getShopOrderById(id);
    }

    public List<Map<String,Object>>	getShopOrderDetails(String id)throws Exception{
        return shopOrderClient.getShopOrderDetails(id);
    }

    public List<Map<String,Object>>	getShopOrderByMap(Map<String,Object> param)throws Exception{
        return shopOrderClient.getShopOrderByMap(param);
    }


    public Integer getShopOrderCountByMap(Map<String,Object> param)throws Exception{
        return shopOrderClient.getShopOrderCountByMap(param);
    }

    public Integer itriptxAddShopOrder(ShopOrder shopOrder)throws Exception{
        return shopOrderClient.itriptxAddShopOrder(shopOrder);
    }

    public Integer itriptxModifyShopOrder(ShopOrder shopOrder)throws Exception{
        return shopOrderClient.itriptxModifyShopOrder(shopOrder);
    }

    public Integer itriptxDeleteShopOrderById(Long id)throws Exception{
        return shopOrderClient.itriptxDeleteShopOrderById(id);
    }

    public Page<ShopOrder> queryShopOrderPageByMap(Map<String,Object> param, Integer pageNo, Integer pageSize)throws Exception{
        Integer total = shopOrderClient.getShopOrderCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Map<String, Object>> shopOrderList = shopOrderClient.getShopOrderByMap(param);
        for(Map<String, Object> a:shopOrderList){
            Map<String, String> map = repairUserClient.getRepairAddressById(a.get("rep_user_id").toString(), a.get("address").toString());
            if(EmptyUtils.isNotEmpty(map)){
                a.put("nickname", map.get("nickname"));a.put("phone", map.get("phone"));a.put("address", map.get("address"));
                a.put("provinceName", map.get("provinceName"));a.put("cityName", map.get("cityName"));a.put("areaName", map.get("areaName"));
            }
        }
        page.setRows(shopOrderList);
        return page;
    }

    /**
     * 分页查询经销商销售订单
     * @param param
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public Page<ShopOrder> queryShopOrderAgentPageByMap(Map<String,Object> param, Integer pageNo, Integer pageSize)throws Exception{
        Integer total = shopOrderClient.getShopOrderCountAgentByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Map<String, Object>> shopOrderList = shopOrderClient.getShopOrderAgentByMap(param);
        for(Map<String, Object> a:shopOrderList){
            Map<String, String> map = repairUserClient.getRepairAddressById(a.get("rep_user_id").toString(), a.get("address").toString());
            if(EmptyUtils.isNotEmpty(map)){
                a.put("nickname", map.get("nickname"));a.put("phone", map.get("phone"));a.put("address", map.get("address"));
                a.put("provinceName", map.get("provinceName"));a.put("cityName", map.get("cityName"));a.put("areaName", map.get("areaName"));
            }
        }
        page.setRows(shopOrderList);
        return page;
    }


    @Override
    public Dto submitOrder(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
            ShopOrder order = new ShopOrder();
            String orderId = IdWorker.getId();
            order.setId(orderId);
            order.setState("0");
            String dataStr = request.getParameter("data");
            JSONObject jso = JSONObject.parseObject(dataStr);
            JSONArray array = jso.getJSONArray("products");
            String[] proIds = new String[array.size()];
            for(int i = 0;i<array.size();i++){
                JSONObject projson = array.getJSONObject(i);
                proIds[i] = projson.getString("id");
            }
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("ids",proIds);
            List<String> strList = shopOrderClient.getShopIds(param);
            if(strList.size()>1){
                return  DtoUtil.returnFail("购物车只能提交一个店铺的商品","002");
            }
            Map<String,Object> userMap =JSONObject.parseObject(jso.getString("user"));
            Map<String,Object> ordMap = JSONObject.parseObject(jso.getString("order"));
            order.setAddress(userMap.get("addressId").toString());
            order.setCountMoney(ordMap.get("privace").toString());
            order.setRepUserId(user.getId());
            order.setSendTypeId(ordMap.get("send_type").toString());
            order.setCreateTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            order.setOrderNumber(createOrderNo(order));
            if(EmptyUtils.isNotEmpty(ordMap.get("carId"))){
                order.setCarId(ordMap.get("carId").toString());
            }
                shopOrderClient.insertShopOrder(order);
            if(EmptyUtils.isNotEmpty(ordMap.get("carId"))){
                String Carid = ordMap.get("carId").toString();
                for(int n=0;n<array.size();n++){
                    Map<String,Object> paramMap =new HashMap<String,Object>();
                    paramMap.put("carId",Carid);
                    paramMap.put("product_id",array.getJSONObject(n).getString("id"));
                    shopOrderClient.updateCarProListState(paramMap);
                }
                int n= shopOrderClient.getCarProCun(Carid);
                if(n==0){
                    shopOrderClient.updateCarStateFin(Carid);
                }
            }
            for(int i = 0;i<array.size();i++){
                JSONObject projson = array.getJSONObject(i);
                Map<String,Object> pro = new HashMap<String, Object>();
                pro.put("id",IdWorker.getId());
                pro.put("order_id",orderId);
                pro.put("product_id",projson.getString("id"));
                pro.put("pro_price",projson.getString("price"));
                pro.put("pro_count",projson.getString("count"));
                pro.put("create_time",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                shopOrderClient.insertOrder_pro_rel(pro);
            }
            return  DtoUtil.returnDataSuccess(orderId);
    }
    private String createOrderNo(ShopOrder order) {
        StringBuilder md5String = new StringBuilder();
        md5String.append(order.getId());
        md5String.append(order.getRepUserId());
        md5String.append(System.currentTimeMillis());
        md5String.append(Math.random() * 1000000);
        String md5 = MD5.getMd5(md5String.toString(), 6);
        //生成订单编号
        StringBuilder orderNo = new StringBuilder();
        try {
            orderNo.append(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        orderNo.append(md5);
        return orderNo.toString();
    }
    @Override
    public Dto getOrdInfoById(String orderId, HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto plantGetOrdInfoById(HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto getOrdInfoByUserId(HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto evaluate(HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto getEvaluateByOrderId(HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto hasGetPro(HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto cancelOrder(HttpServletRequest request) {
        return null;
    }
}
